/**
 * Created by ziyu on 17/3/9.
 */

import React, {Component, PropTypes} from 'react'
import {Form, Input, Button, DatePicker, Select, Icon, Radio, Row, Col, Checkbox} from 'antd'
import {fetchPost} from '../../../utils/request'
import Styles from '../less/search.less'
import moment from 'moment'

const FormItem = Form.Item
const RadioButton = Radio.Button
const RadioGroup = Radio.Group
const Option = Select.Option
const {RangePicker} = DatePicker
const dateFormat = 'YYYY-MM-DD'
const dateFormatTime = 'YYYY-MM-DD HH:mm'
const CheckboxGroup = Checkbox.Group

class Search extends React.Component {
  /*
  父元素传递参数格式
   {
     list: [
       {
       name: 'label名称',
       type: '控件类型(select text range buttonRadio search group)',
       key: '参数字段'(若为range, 传入数组['startDate','endDate'] 若为group 传入数组['findtype','inputValue']),
       className: '控件样式,多个样式以空格分割',
       values: [] //若是select,buttonRadio多传一个空数组接收options的值
       }
     ],
     api: '获取数据接口地址'
   }
   */
  constructor(props) {
    super(props)

    let checkboxMap = {}
    let params = props.searchParams
    if (params && params.list) {
      params.list.forEach((value, index) => {
        if (value.type === 'checkbox') {
          value.indeterminate = false
          value.checkAll = true
          let checkedList = []
          value.values.map((val, ind) => {
            checkedList.push(val.value)
          })
          value.checkedList = checkedList
          checkboxMap[value.key] = value
        }
      })
    }

    this.state = {
      params: props.searchParams,
      data: {},
      initStates: {},
      pathHash: '',
      pathFinance: '',
      pathAffairs: '',
      stepType: props.stepType,
      checkboxMap: checkboxMap
    }

    this.initParams = this.initParams.bind(this)
  }

  componentDidMount() {
    this.initParams()
  }

  componentWillReceiveProps(props) {
    if (this.state.params !== props.searchParams) {

      let checkboxMap = {}
      let params = props.searchParams
      if (params && params.list) {
        params.list.forEach((value, index) => {
          if (value.type === 'checkbox') {
            value.indeterminate = false
            value.checkAll = true
            let checkedList = []
            value.values.map((val, ind) => {
              checkedList.push(val.value)
            })
            value.checkedList = checkedList
            checkboxMap[value.key] = value
          }
        })
      }

      this.setState({
        checkboxMap: checkboxMap,
        params: params
      }, () => {
        this.initParams()
      })
    }
  }

  componentWillMount() {
    this.pathHash = window.location.hash.substring(window.location.hash.indexOf('#') + 1, window.location.hash.indexOf('?'))
    this.pathFinance = window.location.hash.substring(window.location.hash.indexOf('finance'), window.location.hash.indexOf('finance') + 7)
    this.pathAffairs = window.location.hash.substring(window.location.hash.indexOf('affairs'), window.location.hash.indexOf('affairs') + 7)
    // console.log(this.pathAffairs, this.pathFinance)
  }

  initParams() {
    if (this.state.params.api) {
      fetchPost(`${this.state.params.api}`).then((res) => {
        this.state.params.list.forEach((value, index) => {
          if (value.type === 'checkbox') {
            value.indeterminate = false
            value.checkAll = true
          }

          for (let i in res.data) {
            switch (value.type) {
              case 'group':
                if (value.key[0] == i) {
                  value.values = value.values.concat(res.data[i])
                }
                break
              case 'range':
                if (value.values && !value.values.length && this.pathHash !== '/overdue/personalCheck') {
                  value.values = [
                    moment().subtract('days', 7),
                    moment()
                  ]
                }
                break
              case 'newSelect':
                if (value.key == i) {
                  value.values = value.values.concat(res.data[i])
                }
                break
              default:
                if (value.key === i) {
                  value.values = value.values.concat(res.data[i])
                }
            }
          }
        })
        this.initState(this.state.params.list)
      })
    } else {
      this.state.params.list.forEach((value, index) => {
        if (value.type === 'range') {
          if (value.values && !value.values.length && this.pathHash !== '/overdue/personalCheck') {
            value.values = [
              moment().subtract('days', 7),
              moment()
            ]
          }
        }
      })
      this.initState(this.state.params.list)
    }
  }

  initState(list) {
    let initStates = {}
    for (let i in list) {
      let value = list[i]
      if (typeof value.key === 'object') {
        if (value.type === 'range') {
          let start = value.key[0]
          let end = value.key[1]
          if (this.pathHash !== '/overdue/personalCheck') {
            initStates[start] = value.values[0].format(dateFormat)
            initStates[end] = value.values[1].format(dateFormat)
          } else {
            initStates[start] = null
            initStates[end] = null
          }
        } else {
          value.key.forEach((val, ind) => {
            initStates[val] = ''
          })
        }
      } else {
        initStates[value.key] = ''
      }
    }
    this.setState({
      data: initStates,
      initStates
    })
  }

  changeTime(time, keys) {
    if (time.length) {
      let startDate = time[0].format(dateFormat)
      let endDate = time[1].format(dateFormat)
      this.setState({
        data: {
          ...this.state.data,
          [keys[0]]: startDate,
          [keys[1]]: endDate
        }
      }, () => {
        this.copyState()
      })
    } else {
      this.setState({
        ...this.state.data,
        startDate: '',
        endDate: ''
      }, () => {
        this.copyState()
      })
    }
  }

  changeRangeTime(time, keys) {
    if (time.length) {
      let startDate = time[0].format(dateFormatTime)
      let endDate = time[1].format(dateFormatTime)
      this.setState({
        data: {
          ...this.state.data,
          [keys[0]]: startDate,
          [keys[1]]: endDate
        }
      }, () => {
        this.copyState()
      })
    } else {
      this.setState({
        ...this.state.data,
        startDate: '',
        endDate: ''
      }, () => {
        this.copyState()
      })
    }
  }

  copyState() {
    let copyState = {}
    for (let i in this.state.data) {
      if (this.state.data[i] !== '') {
        copyState[i] = this.state.data[i]
      }
    }
    this.props.changeParams(copyState)
  }

  primaryBtnClick() {
    this.props.primaryBtnClick()
  }

  groupSearch() {
    let btnSearchParams = {}
    this.state.params.list.forEach((value, index) => {
      switch (value.type) {
        case 'text':
          btnSearchParams[value.key] = this.props.form.getFieldValue(value.key)
          break

        case 'group':
          value.key.forEach((val, ind) => {
            btnSearchParams[val] = this.props.form.getFieldValue(val)
          })
          break
        default:
      }
    })
    this.setState({
      data: {
        ...this.state.data,
        ...btnSearchParams
      }
    }, () => {
      this.copyState()
    })
  }

  // 新的searchBtn
  // 逻辑 参数改变不出发search, 只有search button 发生click才触发search接口
  newSearchBtn() {
    let btnSearchParams = {}
    this.state.params.list.forEach((value, index) => {
      switch (value.type) {
        case 'text':
          btnSearchParams[value.key] = this.props.form.getFieldValue(value.key)
          break

        case 'group':
          value.key.forEach((val, ind) => {
            btnSearchParams[val] = this.props.form.getFieldValue(val)
          })
          break
        default:
      }
    })
    this.setState({
      data: {
        ...this.state.data,
        ...btnSearchParams
      }
    }, () => {
      let copyState = {}
      for (let i in this.state.data) {
        if (this.state.data[i] !== '') {
          copyState[i] = this.state.data[i]
        }
      }
      this.props.searchFunc(copyState)
    })
  }

  changeField(field, value) {
    // debugger;
    this.setState({
      data: {
        ...this.state.data,
        [field]: value
      }
    }, () => {
      this.copyState()
    })
  }

  changeDate(e, field) {
    const date = e.format(dateFormat)
    this.setState({
      data: {
        ...this.state.data,
        [field]: date
      }
    }, () => {
      this.copyState()
    })
  }

  checkboxChange(checkedList, key) {
    let checkboxMap = this.state.checkboxMap
    checkboxMap[key].checkedList = checkedList
    checkboxMap[key].indeterminate = !!checkedList.length && (checkedList.length < this.getCheckboxOptionsList(key).length)
    checkboxMap[key].checkAll = checkedList.length === this.getCheckboxOptionsList(key).length
    this.setState({
      checkboxMap: checkboxMap
    })

    this.setState({
      data: {
        ...this.state.data,
        [key]: checkedList
      }
    }, () => {
      this.copyState()
    })
  }

  checkboxCheckAllChange(e, key) {
    let checkboxMap = this.state.checkboxMap
    checkboxMap[key].checkedList = e.target.checked ? this.getCheckboxOptionsList(key) : []
    checkboxMap[key].indeterminate = false
    checkboxMap[key].checkAll = e.target.checked
    this.setState({
      checkboxMap: checkboxMap
    })
  }

  getCheckboxOptionsList(key) {
    let item = this.state.checkboxMap[key]
    let optionsList = []
    if (item) {
      item.values.map((val, ind) => {
        optionsList.push(val.value)
      })
    }
    return optionsList
  }

  handleReset(e) {
    e.preventDefault()
    this.props.form.resetFields()
    this.setState({
      data: this.state.initStates
    }, () => {
      let copyState = {}
      for (let i in this.state.data) {
        if (this.state.data[i] !== '') {
          copyState[i] = this.state.data[i]
        }
      }
      this.props.changeParams(copyState)
    })
  }

  callPut() {
    this.props.callPutButton()
  }

  render() {
    const {getFieldDecorator} = this.props.form
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 18}
    }
    const formItemLayoutButton = {
      labelCol: {span: 0},
      wrapperCol: {span: 24}
    }
    // console.log(this.state.params.list,'this.state.params.list')
    const pathFinance = this.pathFinance
    const pathAffairs = this.pathAffairs
    return (
      <Form inline>
        {
          this.state.params.list.map((value, index) => {
            switch (value.type) {
              case 'group':
                return (
                  <span key='100'>
                    <FormItem
                      className={`${value.className} ${Styles.itemWrapper}`}
                      label={value.name}
                    >
                      {getFieldDecorator(`${value.key[0]}`, {initialValue: ''})(
                        <Select placeholder='请选择' style={{width: 100}}>
                          {
                            value.values.map((val, ind) => {
                              return (<Option key={ind} value={val.value.toString()}>{val.name}</Option>)
                            })
                          }
                        </Select>
                      )}
                    </FormItem>

                    <FormItem className={`${Styles.itemWrapper}`} key='101'>
                      {getFieldDecorator(`${value.key[1]}`)(
                        <Input placeholder='Please input'
                               style={{width: 180}}/>
                      )}
                    </FormItem>
                  </span>
                )
              case 'select':
                if (!(this.state.stepType != null && typeof (this.state.stepType) !== 'undefined' && this.state.stepType == 'photoCheckReupload')) {
                  if (value.key == 'isReupload') {
                    return null
                  }
                }
                return (
                  <FormItem
                    className={`${value.className} ${Styles.itemWrapper}`}
                    label={value.name}
                    key={index}
                  >
                    {getFieldDecorator(`${value.key}`,
                      {
                        initialValue: value.defaultValue ?
                          value.defaultValue :
                          (value.key == 'isReupload' ? '9' : value.key == 'orderType' ? '0' : '')
                      })(
                      <Select onChange={(e) => this.changeField(`${value.key}`, e)} placeholder='Please Select'
                              style={value.key == 'isReupload' || value.key == 'fundCode' || value.key == 'stageCode' ? {width: 200} : {width: 100}}
                              showSearch={true}
                              optionFilterProp="children"
                              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      >
                        {
                          value.values.map((val, ind) => {
                            return (<Option key={ind} value={val.value.toString()}>{val.name}</Option>)
                          })
                        }
                      </Select>
                    )}
                  </FormItem>
                )

              case 'checkbox':
                return (
                  <FormItem
                    className={`${value.className} ${Styles.itemWrapper}`}
                    label={value.name}
                    key={index}
                  >
                    {getFieldDecorator(`${value.key}`,
                      {
                        initialValue: value.defaultValue ? value.defaultValue : this.getCheckboxOptionsList(value.key)
                      })(
                      <div>
                        {/*<Checkbox*/}
                        {/*  indeterminate={this.state.checkboxMap[value.key].indeterminate}*/}
                        {/*  onChange={(e) => this.checkboxCheckAllChange(e, value.key)}*/}
                        {/*  checked={this.state.checkboxMap[value.key].checkAll}*/}
                        {/*>*/}
                        {/*  Check all*/}
                        {/*</Checkbox>*/}
                        <CheckboxGroup options={this.getCheckboxOptionsList(value.key)}
                                       value={this.state.checkboxMap[value.key].checkedList}
                                       onChange={(e) => this.checkboxChange(e, value.key)}/>
                      </div>
                    )}
                  </FormItem>
                )

              case 'newSelect':
                return (
                  <FormItem
                    className={`${value.className} ${Styles.itemWrapper}`}
                    label={value.name}
                    key={index}
                  >
                    {getFieldDecorator(`${value.key}`,
                      {initialValue: ''})(
                      <Select onChange={(e) => this.changeField(`${value.key}`, e)} placeholder='Please select'
                              style={{width: 500}}
                      >
                        {
                          value.values.map((val, ind) => {
                            return (<Option key={ind} value={val.value.toString()}>{val.name}</Option>)
                          })
                        }
                      </Select>
                    )}
                  </FormItem>
                )

              case 'multipleSelect':
                console.log('--multipleSelect--', value)
                return (
                  <FormItem
                    className={`${value.className} ${Styles.itemWrapper}`}
                    label={value.name}
                    key={index}
                  >
                    {getFieldDecorator(`${value.key}`, {initialValue: []})(
                      <Select mode='multiple' onChange={(e) => this.changeField(`${value.key}`, e)} placeholder='请选择'
                              style={{width: 180}}>
                        {
                          value.values.map((val, index) => {
                            return (<Option key={index} value={val.value}>{val.name}</Option>)
                          })
                        }
                      </Select>
                    )}
                  </FormItem>
                )

              case 'text':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} key={index} label={value.name}>
                    {getFieldDecorator(`${value.key}`)(
                      <Input placeholder={value.placeHolder} style={{width: 180}}/>
                    )}
                  </FormItem>
                )

              case 'range':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} label={value.name} key={index}>
                    {getFieldDecorator(`${value.key[0]}`, {initialValue: value.values})(
                      <RangePicker onChange={(e) => {
                        this.changeTime(e, value.key)
                      }} allowClear={false}/>
                    )}
                  </FormItem>
                )
              case 'range-time':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} label={value.name} key={index}>
                    {getFieldDecorator(`${value.key[0]}`, {initialValue: value.values})(
                      <RangePicker onChange={(e) => {
                        this.changeRangeTime(e, value.key)
                      }} allowClear={false} showTime={{format: 'HH:mm'}} format='YYYY-MM-DD HH:mm'/>
                    )}
                  </FormItem>
                )

              case 'date':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} label={value.name} key={index}>
                    {getFieldDecorator(`${value.key}`, {initialValue: value.values})(
                      <DatePicker onChange={(e) => this.changeDate(e, value.key)}/>
                    )}
                  </FormItem>
                )

              case 'buttonRadio':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} label={value.name} key={index}>
                    {getFieldDecorator(`${value.key}`, {
                      initialValue: pathFinance === 'finance' || pathAffairs === 'affairs' ? '' : null
                    })(
                      <RadioGroup onChange={(e) => this.changeField(`${value.key}`, e.target.value)}>
                        {
                          value.values.map((val, ind) => {
                            return (
                              <RadioButton key={ind} value={val.value}>{val.name}</RadioButton>
                            )
                          })
                        }
                      </RadioGroup>
                    )}
                  </FormItem>
                )
              case 'search':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} key='102'>
                    <Button type='primary' icon='search' onClick={() => {
                      this.groupSearch()
                    }}>Search</Button>
                  </FormItem>
                )

              case 'searchBtn':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`} key='103'>
                    <Button type='primary' icon='search' onClick={() => {
                      this.newSearchBtn()
                    }}>Search</Button>
                  </FormItem>
                )

              case 'button':
                return (
                  <FormItem className={`${value.className} ${Styles.itemWrapper}`}>
                    <Button type='primary' onClick={() => {
                      this.primaryBtnClick()
                    }}>{value.name}</Button>
                  </FormItem>
                )

              default:
            }
          })
        }
        <FormItem className={Styles.refreshBtn}>
          <Button type='ghost' onClick={(e) => this.handleReset(e)}><Icon type='reload'/></Button>
        </FormItem>
        {
          this.props.button
            ? <FormItem>
              <Button style={{marginLeft: 10, marginTop: 5}} type='primary' onClick={() => this.callPut()}>
                <Icon type='phone' size='20'/>
              </Button><span style={{marginLeft: 10}} id='ztth_phone_error'/>
            </FormItem>
            : <FormItem/>
        }

      </Form>

    )
  }
}

Search = Form.create()(Search)
export default Search
